package com.shuiyun.chat.handler;

import cn.hutool.core.util.ObjectUtil;
import com.shuiyun.chat.entity.message.LoginRequestMessage;
import com.shuiyun.chat.entity.message.LoginResponseMessage;
import com.shuiyun.chat.entity.message.ReceiveGroupMessage;
import com.shuiyun.chat.entity.message.SimpleChatMessage;
import com.shuiyun.chat.entity.vo.UserVO;
import com.shuiyun.chat.enums.ChatSessionKey;
import com.shuiyun.chat.service.UserService;
import com.shuiyun.chat.utils.RedisUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author shuiyun
 * @program oicq
 * @description 登录处理器
 * @create 2021-05-12 16:52
 **/
@Slf4j
@ChannelHandler.Sharable
@Component
public class LoginHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestMessage loginMessage) throws Exception {
        // 校验账号和密码
        UserVO user = userService.findByUserName(loginMessage.getUserName());
        if (null == user){
            log.error("用户名不存在，登录失败!");
            channelHandlerContext.channel().writeAndFlush(new LoginResponseMessage(false,"用户名不存在"));
            return;
        }
        if (!user.getPassword().equals(loginMessage.getPassword())){
            log.error("用户密码不正确！");
            channelHandlerContext.channel().writeAndFlush(new LoginResponseMessage(false,"用户密码不正确"));
            return;
        }
        channelHandlerContext.channel().writeAndFlush(new LoginResponseMessage(true,"登录成功"));
        userService.bind(user,channelHandlerContext.channel());
        log.info("{} 上线了!!",user.getNickName());
        // 增加后续逻辑 等用户上线之后 查看是否存在待接收消息 如果存在 则开始发送
        // 私聊消息
        SimpleChatMessage simpleChatMessage = redisUtil.leftPop(ChatSessionKey.simpleChat.getKey() + user.getUserName(), SimpleChatMessage.class);
        while (ObjectUtil.isNotNull(simpleChatMessage)){
            channelHandlerContext.channel().writeAndFlush(simpleChatMessage);
            simpleChatMessage = redisUtil.leftPop(ChatSessionKey.simpleChat.getKey() + user.getUserName(), SimpleChatMessage.class);
        }
        // 群消息
        ReceiveGroupMessage groupMessage = redisUtil.leftPop(ChatSessionKey.groupChat.getKey() + user.getUserName(), ReceiveGroupMessage.class);
        while (ObjectUtil.isNotNull(groupMessage)){
            channelHandlerContext.channel().writeAndFlush(groupMessage);
            groupMessage = redisUtil.leftPop(ChatSessionKey.groupChat.getKey() + user.getUserName(), ReceiveGroupMessage.class);
        }

    }
}
